package ly.gupao.edu.java8.MyCollections;

import ly.gupao.edu.java8.MyCollections.PrimeNumbersCollector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.partitioningBy;

/**
 * @author: liyang
 * @date：2018/10/17 0017
 * describe：
 */
public class Test {

//    public static void main(String[] args) {
//
//        StopWatch stopWatch = new StopWatch();
//        stopWatch.start("优化前");
//        Test test = new Test();
//        Map<Boolean, List<Integer>> map = IntStream.rangeClosed(2, 1_000_000)
//                .boxed().collect(partitioningBy(e -> test.isPrimy(e)));
//        stopWatch.stop();
//        System.out.println(stopWatch.prettyPrint());
//
//    }

//    public static void main(String[] args) {
//        long fastest = Long.MAX_VALUE;
//        for (int i = 0; i < 10; i++) {
//            long start = System.nanoTime();
//            partitionPrimesWithCustomCollector(1_000_000);
//            long duration = (System.nanoTime() - start) / 1_000_000;
//            if (duration < fastest) fastest = duration;
//        }
//        System.out.println(
//                "Fastest execution done in " + fastest + " msecs");
//    }

    public static void main(String[] args) {
        HashMap<Boolean, List<Integer>> collect = IntStream.rangeClosed(2, 100)
                .boxed()
                .collect(() -> new HashMap<Boolean, List<Integer>>() {{
                    put(true, new ArrayList<>());
                    put(false, new ArrayList<>());
                }},
                (acc, contidate) -> {
                    acc.get(PrimeNumbersCollector.isPrime(acc.get(true), contidate))
                            .add(contidate);
                },
                (map1, map2) -> {
                    map1.get(true).addAll(map2.get(true));
                    map1.get(false).addAll(map2.get(false));
                }
                );
        System.out.println(collect);
    }

    public static Map<Boolean, List<Integer>> partitionPrimesWithCustomCollector(int n) {
        return IntStream.rangeClosed(2, n).boxed()
                .collect(new PrimeNumbersCollector());
    }

    public boolean isPrimy(int candidate){
        return IntStream.range(2, candidate)
                .noneMatch( i -> candidate % i == 0);
    }

}
